<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart"></div>
    <div v-if="$route.path === '/page5'" class="conclusion-box">
      <h3>全球开发者分布</h3>
      <div v-html="conclusionContent"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import "echarts-gl";
import axios from "axios";

const chartRef = ref(null);
let myChart = null;
const conclusionContent = ref(""); // 响应式变量，用于存储结论内容
const chartData = ref([]); // 响应式变量，用于存储图表数据

const API_ENDPOINT = "http://127.0.0.1:8080/api/country-dev-salary/stats";
const CONCLUSION_ENDPOINT = "http://127.0.0.1:8080/api/country-dev-salary/conclusion";

// 国家坐标映射表
const countryCoordinates = {
  // Asia
  "China": [116.46, 39.92],
  "Japan": [138.252924, 36.204824],
  "South Korea": [127.766922, 35.907757],
  "India": [78.96288, 20.593684],
  "Indonesia": [113.921327, -0.789275],
  "Thailand": [100.992541, 15.870032],
  "Vietnam": [108.277199, 14.058324],
  "Malaysia": [101.975766, 4.210484],
  "Singapore": [103.819836, 1.352083],
  "Philippines": [121.774017, 12.879721],
  "Pakistan": [69.345116, 30.375321],
  "Bangladesh": [90.356331, 23.684994],
  "Saudi Arabia": [45.079162, 23.885942],
  "Iran": [53.688046, 32.427908],
  "Turkey": [35.243322, 38.963745],
  "Israel": [34.851612, 31.046051],
  "United Arab Emirates": [53.847818, 23.424076],

  // Europe
  "United Kingdom": [-3.435973, 55.378051],
  "France": [2.213749, 46.227638],
  "Germany": [10.451526, 51.165691],
  "Italy": [12.56738, 41.87194],
  "Spain": [-3.74922, 40.463667],
  "Portugal": [-8.224454, 39.399872],
  "Netherlands": [5.291266, 52.132633],
  "Belgium": [4.469936, 50.503887],
  "Switzerland": [8.227512, 46.818188],
  "Austria": [14.550072, 47.516231],
  "Sweden": [18.643501, 60.128161],
  "Norway": [8.468946, 60.472024],
  "Finland": [25.748151, 61.92411],
  "Denmark": [9.501785, 56.26392],
  "Russia": [105.318756, 61.52401],
  "Poland": [19.145136, 51.919438],
  "Ukraine": [31.16558, 48.379433],

  // North America
  "United States": [-95.712891, 37.09024],
  "Canada": [-106.346771, 56.130366],
  "Mexico": [-102.552784, 23.634501],
  "Cuba": [-77.781167, 21.521757],
  "Panama": [-80.782127, 8.537981],
  "Costa Rica": [-83.753428, 9.748917],

  // South America
  "Brazil": [-51.92528, -14.235004],
  "Argentina": [-63.616672, -38.416097],
  "Chile": [-71.542969, -35.675147],
  "Colombia": [-74.297333, 4.570868],
  "Peru": [-75.015152, -9.189967],
  "Venezuela": [-66.58973, 6.42375],

  // Africa
  "South Africa": [22.937506, -30.559482],
  "Egypt": [30.802498, 26.820553],
  "Nigeria": [8.675277, 9.081999],
  "Kenya": [37.906193, -0.023559],
  "Ethiopia": [40.489673, 9.145],
  "Morocco": [-7.09262, 31.791702],
  "Algeria": [1.659626, 28.033886],

  // Oceania
  "Australia": [133.775136, -25.274398],
  "New Zealand": [174.885971, -40.900557],
  "Fiji": [178.065032, -17.713371],
  "Papua New Guinea": [143.95555, -6.314993],

  // Other regions
  "Greenland": [-42.604303, 71.706936],
  "Iceland": [-19.020835, 64.963051],
  "Madagascar": [46.869107, -18.766947],
  "Sri Lanka": [7.50, 80]
};

// 颜色集合
const colorPalette = [
  "#FF6384", "#36A2EB", "#FFCE56", "#4BC0C0", "#9966FF",
  "#FF9F40", "#8AC24A", "#F06292", "#7986CB", "#4DB6AC"
];

// 获取数据函数
const fetchData = async () => {
  try {
    const response = await axios.get(API_ENDPOINT);
    return response.data;
  } catch (err) {
    console.error("获取图表数据失败:", err);
    throw err;
  }
};

// 获取随机颜色
const getRandomColor = () => {
  return colorPalette[Math.floor(Math.random() * colorPalette.length)];
};

// 获取结论内容
const fetchConclusion = async () => {
  try {
    const response = await axios.get(CONCLUSION_ENDPOINT);
    if (response.data.code !== 0) {
      throw new Error(response.data.message || "结论接口返回错误");
    }
    conclusionContent.value = response.data.data; // 更新结论内容
  } catch (err) {
    console.error("加载结论失败:", err);
    throw err;
  }
};

onMounted(async () => {
  if (!chartRef.value) {
    console.error("chartRef.value is null. Please check the ref binding.");
    return;
  }

  myChart = echarts.init(chartRef.value);

  try {
    const apiData = await fetchData();

    if (!Array.isArray(apiData.data)) {
      throw new Error("返回数据格式不正确");
    }

    const series = apiData.data.map((item, index) => {
      const countryName = item.country;
      const coordinates = countryCoordinates[countryName] || [0, 0]; // 默认坐标为太平洋中部

      return {
        name: countryName,
        type: "scatter3D",
        coordinateSystem: "globe",
        blendMode: "lighter",
        symbolSize: Math.min(16 + item.Count / 10, 40), // 根据Count调整大小
        itemStyle: {
          color: getRandomColor(),
          opacity: 0.9,
          borderWidth: 1,
          borderColor: "rgba(255,255,255,0.8)",
        },
        label: {
          show: true,
          position: "right",
          formatter: `${countryName}•${item.avgSalary}`,
          textStyle: {
            color: "#fff",
            borderWidth: 0,
            borderColor: "#fff",
            fontFamily: "sans-serif",
            fontSize: 14,
            fontWeight: "bold",
          },
        },
        data: [[coordinates[0], coordinates[1], 0]],
        totalCount: item.Count,
        avgSalary: item.avgSalary,
      };
    });

    series.sort((a, b) => b.totalCount - a.totalCount);

    const option = {
      title: {
        text: "全球国家数据分布",
        subtext: "国家名称•参与人数",
        left: "center",
        textStyle: {
          color: "#fff",
          fontSize: 22,
          fontWeight: "bold",
          textShadowColor: "#000",
          textShadowBlur: 8
        },
        subtextStyle: {
          color: "#fff",
          fontSize: 16,
          textShadowColor: "#000",
          textShadowBlur: 6
        },
      },
      // legend: {
      //   selectedMode: "multiple",
      //   x: "right",
      //   y: "bottom",
      //   data: apiData.data.map(item => item.country),
      //   padding: [0, 50, 80, 0],
      //   orient: "vertical",
      //   textStyle: {
      //     color: "#fff",
      //     fontSize: 16,
      //     fontWeight: "bold",
      //     textShadowColor: "#000",
      //     textShadowBlur: 6
      //   },
      // },
      backgroundColor: "#058198",
      tooltip: {
        backgroundColor: "#1e2330",
        borderColor: "#1e90ff",
        textStyle: {
          color: "#fff",
          fontSize: 16,
          fontWeight: "bold"
        },
        formatter: (params) => {
          const data = params.seriesData[0];
          return `
            <strong style='color:#1e90ff;'>${params.name}</strong><br/>
            <span style='color:#fff;'>总人数: ${data.totalCount}</span><br/>
            <span style='color:#fff;'>平均薪资: ${data.avgSalary}</span>
          `;
        }
      },
      globe: {
        baseTexture: "https://img.isqqw.com/profile/upload/2024/08/14/457367a4-16b6-453f-9894-baa2eb3e9503.png",
        heightTexture: "https://img.isqqw.com/profile/upload/2024/08/14/457367a4-16b6-453f-9894-baa2eb3e9503.png",
        shading: "color",
        environment: "https://img.isqqw.com/profile/upload/2024/08/14/457367a4-16b6-453f-9894-baa2eb3e9503.png",
        viewControl: {
          autoRotate: true,
          autoRotateSpeed: 3,
          autoRotateAfterStill: 2,
          rotateSensitivity: 2,
          targetCoord: [116.46, 39.92], // 默认指向中国
          maxDistance: 200,
          minDistance: 200,
        },
        light: {
          main: {
            intensity: 1.5,
            shadow: true,
            shadowQuality: "high",
            alpha: 30,
            beta: 40,
          },
          ambient: {
            intensity: 0.7,
          },
        },
      },
      series: series.map(item => ({
        ...item,
        itemStyle: {
          ...item.itemStyle,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          ...item.label,
          show: true,
          position: "right",
          formatter: `${item.name}•${item.avgSalary}`,
          textStyle: {
            color: "#fff",
            borderWidth: 0,
            borderColor: "#fff",
            fontFamily: "sans-serif",
            fontSize: 16,
            fontWeight: "bold",
            textShadowColor: "#000",
            textShadowBlur: 6
          },
        },
      })),
    };

    myChart.setOption(option);

    myChart.on("click", (params) => {
      if (params.seriesType === "scatter3D") {
        const updatedSeries = series.map((item) => {
          if (item.name === params.name) {
            return {
              ...item,
              itemStyle: {
                ...item.itemStyle,
                color: "#FFD700", // 点击后颜色变为金色
                opacity: 1,
              },
              symbolSize: Math.min(20 + item.totalCount / 10, 45), // 稍微放大
            };
          }
          return {
            ...item,
            itemStyle: {
              ...item.itemStyle,
              opacity: 0.7, // 其他点透明度降低
            }
          };
        });

        myChart.setOption({
          series: updatedSeries,
          globe: {
            viewControl: {
              targetCoord: params.data[0].slice(0, 2), // 视角转向点击的国家
            }
          }
        });

        console.log(`国家: ${params.name}, 总人数: ${params.seriesData[0].count}, 平均薪资: ${params.seriesData[0].avgSalary}`);
      }
    });

    window.addEventListener("resize", () => {
      myChart.resize();
    });

  } catch (err) {
    console.error("图表初始化失败:", err);

    myChart.setOption({
      graphic: {
        type: "text",
        left: "center",
        top: "middle",
        style: {
          text: "数据加载失败\n" + err.message,
          fill: "#ff0000",
          fontSize: 14,
          fontWeight: "bold",
        },
      },
    });
  } finally {
    await fetchConclusion(); // 加载结论内容
  }
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", () => myChart.resize());
  myChart.dispose();
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  margin: 20px auto;
  border-radius: 15px;
  box-shadow: 0 8px 20px rgba(21, 19, 48, 0.2);
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative;
}

.chart-container:hover {
  transform: scale(1.02);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);
}

.chart {
  width: 100%;
  height: 100%;
  border-radius: 10px;
  box-shadow: inset 0 4px 10px rgba(0, 0, 0, 0.1);
}

.conclusion-box {
  margin-top: 20px;
  padding: 15px;
  width: 90%;
  max-width: 800px;
  background: rgba(20, 40, 70, 0.95);
  border: 2px solid #1e90ff;
  border-radius: 8px;
  color: #fff;
}

.conclusion-box h3 {
  margin-bottom: 10px;
  font-size: 18px;
  color: #1e90ff;
  text-align: center;
}

.conclusion-box div {
  margin: 8px 0;
  line-height: 1.6;
  color: #fff;
  text-align: left;
}

@media (max-width: 768px) {
  .chart-container {
    height: 500px;
  }
}
</style>